//
//  HomePageSearchViewController.m
//  Taste
//
//  Created by 徐昊 on 16/9/13.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HomePageSearchViewController.h"
#import "ZWYNetTool.h"
#import "SearchModel.h"
#import "SearchRes.h"
#import "SearchTableViewCell.h"
#import "OptionCollectionViewCell.h"
#import "HomPageSearchResultViewController.h"

#define kHomePageSearchTableViewCellName @"HomePageSearchTableViewCellNameReuse"
#define kHomePageSearchCollectionViewCellName @"HomePageSearchCollectionViewCellNameReuse"
@interface HomePageSearchViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *searchRange;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (nonatomic, strong) SearchModel *model;
@property (weak, nonatomic) IBOutlet UIView *optionView;
@property (weak, nonatomic) IBOutlet UILabel *all;
@property (weak, nonatomic) IBOutlet UICollectionView *optionCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSArray *arrayOfName;
@property (nonatomic, strong) NSArray *arrayOfImage;
@property (nonatomic, assign) NSInteger cid;

@end

@implementation HomePageSearchViewController
- (void)viewWillAppear:(BOOL)animated {
    _optionView.alpha = 0;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setup];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHomePageSearchTableViewCellName];
    // 获取当前时间戳
    NSDate *sendDate = [NSDate date];
    NSString *date = [NSString stringWithFormat:@"%ld", (long)[sendDate timeIntervalSince1970]];
    
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : @"26"};
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=Public&a=getTypeForAllIOS" andBody:[NSString stringWithFormat:@"timestamp=%@", date] andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [SearchModel modelWithDic:result];
        [_tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
        
    }];
    _searchRange.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [_searchRange addGestureRecognizer:tap];
    _layout.minimumInteritemSpacing = 0;
    _layout.minimumLineSpacing = 0;
    _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _optionCollectionView.scrollEnabled = NO;
    _optionCollectionView.delegate = self;
    _optionCollectionView.dataSource = self;
    _optionCollectionView.backgroundColor = [UIColor whiteColor];
    [_optionCollectionView registerNib:[UINib nibWithNibName:@"OptionCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:kHomePageSearchCollectionViewCellName];
    _optionCollectionView.layer.masksToBounds = YES;
    _optionCollectionView.layer.cornerRadius = 15;
    
}
- (void)setup {
    _arrayOfName = @[@"全部", @"每日资讯", @"精选餐厅", @"大师菜谱", @"人物志", @"用户"];
    _arrayOfImage = @[@"ImgLib_PopView_Icon_All", @"ImgLib_PopView_Icon_DailyInformation", @"ImgLib_PopView_Icon_Restaurant", @"ImgLib_PopView_Icon_Cookbook", @"ImgLib_PopView_Icon_Master", @"ImgLib_PopView_Icon_ShowField"];
    _textField.returnKeyType = UIReturnKeySearch;
    _textField.enablesReturnKeyAutomatically = YES;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.delegate = self;
    _backView.layer.masksToBounds = YES;
    _backView.layer.cornerRadius = 5;
    _backView.layer.borderColor = [UIColor grayColor].CGColor;
    _backView.layer.borderWidth = 0.5;
    _searchRange.layer.borderWidth = 0.5;
    _searchRange.layer.borderColor = [UIColor grayColor].CGColor;
    _cid = 0;
}
- (void)tap {
    if (_optionView.alpha == 1) {
        _optionView.alpha = 0;
    } else {
        _optionView.alpha = 1;
    }
}

- (IBAction)pop:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - TextField协议
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self resignTextResponder];
    if (textField.returnKeyType == UIReturnKeySearch) {
        if ([_textField.text length] > 0) {
            HomPageSearchResultViewController *vc = [[HomPageSearchResultViewController alloc] init];
            vc.flag = @"1";
            vc.searchString = _textField.text;
            vc.cid = _cid;
            self.tabBarController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            self.tabBarController.hidesBottomBarWhenPushed = NO;
        }
    }
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self resignTextResponder];
}

- (void)resignTextResponder {
    if ([_textField isFirstResponder])
    {
        [_textField resignFirstResponder];
    }
}
#pragma mark - UITableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _model.res.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return _model.res[section].catalog;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomePageSearchTableViewCellName];
    cell.res = _model.res[indexPath.section];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_model.res[indexPath.section].names.count % 3 == 0) {
        return (_model.res[indexPath.section].names.count / 3) * 34;
    } else {
        return (_model.res[indexPath.section].names.count / 3 + 1) * 34;
    }
}

#pragma mark - UICollectionView协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    OptionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kHomePageSearchCollectionViewCellName forIndexPath:indexPath];
    cell.label.text = _arrayOfName[indexPath.row];
    NSString *string = _arrayOfImage[indexPath.row];
    cell.pic.image = [UIImage imageNamed:string];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    _layout.itemSize = CGSizeMake(_optionView.bounds.size.width, _optionView.bounds.size.height / 6);
    return _layout.itemSize;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _all.text = _arrayOfName[indexPath.row];
    _optionView.alpha = 0;
    if (indexPath.row == 0) {
        _cid = 0;
    } else if (indexPath.row == 1) {
        _cid = 1;
    } else if (indexPath.row == 2) {
        _cid = 15;
    } else if (indexPath.row == 3) {
        _cid = 14;
    } else if (indexPath.row == 4) {
        _cid = 16;
    } else if (indexPath.row == 5) {
        _cid = 2;
    }
    
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    _optionView.alpha = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
